<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
    content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>车间多余物料</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="surplus-material">
      <search-btn-view immediate btn-text="查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button size="medium" type="primary" @click="retreatMaterials">批量退回仓库</el-button>
          <el-button v-if="hasApproval" size="medium" type="primary" @click="approvalMaterials">审核过账</el-button>
        </template>
        <div slot="search-content">
          <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:23}"
            :search="search" :search-field="searchField" label-width="100px" input-width="200px">
          </sys-common-search>
        </div>
      </search-btn-view>
      <div class="surplus-material-table-div">
        <el-table fit stripe border :data="materialList" style="width: 100%" height="parent" @selection-change="selectChange">
          <el-table-column fixed :resizable="false" width="50px" type="selection" align="center"></el-table-column>
          <!-- <checkbox-table-column width="90px" header-text="退回仓库" check-field="id" @select-change="retreatSelectChange"
            key="retreatCheckbox"></checkbox-table-column>
          <checkbox-table-column v-if="hasApproval" width="90px" header-text="审核过账" check-field="id"
            @select-change="approvalSelectChange" key="approvalCheckbox"></checkbox-table-column> -->
          <el-table-column sortable label="订单编号" prop="companyOrderId" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="系统订单编号" prop="orderId" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="工厂型号" prop="factoryNo" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="客户型号" prop="customerNo" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable :resizable="false" label="订单序号" prop="lineNo" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.lineNo==='-1'?globalConfig.orderDefaultRowIndex:scope.row.lineNo}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="供应商" prop="providerName" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="物料名称" prop="materialName" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="物料类型" prop="materialType" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="规格型号" prop="model" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="编号" prop="color" min-width="150px" header-align="center"></el-table-column>
          <el-table-column sortable label="物料部门" prop="materialDeptName" min-width="120px" align="center"></el-table-column>
          <el-table-column sortable label="投料数" prop="feedCount" min-width="110px" align="center"></el-table-column>
          <el-table-column sortable label="发料数" prop="receiveCount" min-width="110px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="车间" width="210px" header-align="center">
            <template slot-scope="props">
              <el-cascader filterable style="width:200px" :options="deptWorkList" v-model="props.row.deptWork"
                :props="{value:'id',label:'name'}" separator="-" size="mini"></el-cascader>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="数量" width="180px" header-align="center">
            <template slot-scope="props">
              <el-input-number is-decimal-zero v-model="props.row.materialCount" :min="0.0001" :max="props.row.maxCount"
                :precision="4" :controls="false" size="mini" style="width:170px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="countRatio" label="比例" width="100px" align="center">
          </el-table-column>
          <el-table-column :resizable="false" label="数量(付)" width="180px" align="center">
            <template slot-scope="props">
              <span>{{getFuCount(props.row)}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/sysCommonSearch.css",
    "/vueSystem/components/css/searchBtnView.css"
  ], [
    "/vueSystem/i18n/index.js",
    "/vueSystem/js/permissionUtil.js",
    "/vueSystem/components/sysCommonSearch.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/components/checkboxTableColumn.js",
    "/vueSystem/mixins/tablePaginationMixin.js"
  ]);
</script>

<script>
  var app = new Vue({
    el: '#app',
    mixins: [
      tablePaginationMixin()
    ],

    data: function () {
      var search = {
        orderId: '',
        companyOrderId: '',
        factoryNo: '',
        customerNo: '',
        providerName: '',
        materialName: '',
        model: '',
        color: '',
        materialDept:''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['companyOrderId', 'orderId', 'factoryNo', 'customerNo', 'providerName', 'materialName',
          'model', 'color','materialDept'
        ],
        materialList: [],
        deptWorkList: [],
        selectMaterialList:[],
        hasApproval: false
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkApproval(),
        this.setDeptWorkList()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      checkApproval: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(6).then(function (hasApproval) {
          self.selfApprovalPermission = hasApproval;
          return hasApproval;
        });
      },

      setDeptWorkList: function () {
        var self = this;
        return ajaxRequest('basicData/getWorkshop').then(function (deptWorkList) {
          var deptWorkObj = {};
          for (var i = 0; i < deptWorkList.length; i++) {
            var deptWork = deptWorkList[i];
            var deptId = deptWork.deptId;
            var dataId = 'dept_' + deptId;

            var obj = deptWorkObj[dataId];
            if (obj === undefined) {
              obj = {
                id: deptId,
                dataId: dataId,
                name: deptWork.productionLine
              };
              deptWorkObj[dataId] = obj;
            }

            var children = obj.children;
            if (children === undefined) {
              children = [];
              obj.children = children;
            }
            children.push({
              id: deptWork.id,
              dataId: 'workshop_' + deptWork.id,
              name: deptWork.workshopName
            });
          }

          var deptWorkList = _.values(deptWorkObj);
          self.deptWorkList = deptWorkList;
          return deptWorkList;
        });
      },

      setMaterialList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        postData = {
          start: start,
          length: pageSize
        };

        var fields = ['companyOrderId', 'orderId', 'factoryNo', 'customerNo', 'providerName', 'materialName',
          'model', 'color'
        ];
        var search = this.search;
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('warehouse/workShopNeedReturnMaterial', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var materialList = res.returnData;
          for (var i = 0; i < materialList.length; i++) {
            var material = materialList[i];
            material.deptWork = [];

            var materialCount = material.receiveCount - material.feedCount;
            materialCount = _.round(materialCount, 4);
            material.materialCount = materialCount;
            material.maxCount = materialCount;

            var biLi = material.biLi;
            biLi = _.round(biLi * 100, 0);
            var commonDivisor = SysUtil.getGreatestCommonDivisor(100, biLi);
            var countRatio = `${_.round(100/commonDivisor, 0)}:${_.round(biLi/commonDivisor, 0)}`;
            material.countRatio = countRatio;
            material.id = SysUtil.getId();

            SysUtil.tableSetDeptData(material);
          }

          self.materialList = materialList;
          self.pagination.totalCount = res.iTotalRecords;
          self.selectMaterialList = [];
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialList(true);
      },

      pageChange: function () {
        this.setMaterialList();
      },

      selectChange: function (materialList) {
        this.selectMaterialList = materialList;
      },

      retreatMaterials: function () {
        var materialList = this.selectMaterialList;
        if (materialList.length === 0) {
          this.$alert('请选择需要退回仓库的物料', '信息');
          return;
        }
        this.toHandleMaterialList(materialList, false)
      },

      approvalMaterials: function () {
        var materialList = this.selectMaterialList;
        if (materialList.length === 0) {
          this.$alert('请选择需要审核过账的物料', '信息');
          return;
        }
        this.toHandleMaterialList(materialList, true);
      },

      toHandleMaterialList: function (materialList, isAduit) {
        var postDataList = [];
        for (var i = 0; i < materialList.length; i++) {
          var material = materialList[i];
          var materialPostData = this.getMaterialPostData(material, isAduit);
          if (materialPostData === null) {
            return;
          }
          postDataList.push(materialPostData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest('warehouse/workShopSurplusMaterialReturnToWarehouseAll', {
          jsonArray: JSON.stringify(postDataList),
          isAduit: isAduit
        }).then(function (msg) {
          self.loading = false;
          msg = isAduit ? '物料成功审核过账' : '物料成功退回仓库';
          self.$alert(msg, '信息', {
            callback: function () {
              self.setMaterialList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getMaterialPostData: function (material, isAduit) {
        if (!this.checkValid(material, isAduit)) {
          return null;
        }
        var biLi = material.biLi;
        var qualified = _.round(material.materialCount * biLi, 4);
        qualified = Math.floor(qualified);

        var deptWork = material.deptWork;
        var workshopId = deptWork[deptWork.length - 1];
        var deptId = deptWork[0];
        var postData = {
          workShopName: workshopId,
          deviceId: deptId,
          rowIndex: material.lineNo,
          machining: material.materialType,
          qualified: qualified
        }
        var fields = ['orderId', 'materialCode', 'materialCount'];
        SysUtil.setPostData(postData, material, fields, false, true);
        return postData;
      },

      checkValid: function (material, isAduit) {
        var msg = isAduit ? '审核过账' : '退回';
        var deptWork = material.deptWork;
        if (deptWork.length === 0) {
          this.$alert('请选择从哪个车间' + msg, '信息');
          return false;
        }

        if (material.materialCount === undefined) {
          this.$alert('请输入物料' + msg + '数量', '信息');
          return false;
        }

        var biLi = material.biLi;
        var qualified = _.round(material.materialCount * biLi, 4);
        if (qualified < 1) {
          this.$alert('物料不足一付不可' + msg, '信息');
          return null;
        }
        return true;
      },

      getFuCount: function (material) {
        var materialCount = material.materialCount;
        if (materialCount === undefined) {
          return '';
        }

        var count = _.round(materialCount * material.biLi, 4);
        count = Math.floor(count);
        return count;
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SysCommonSearch: SysCommonSearch,
      CheckboxTableColumn: CheckboxTableColumn
    }
  });
</script>
<style>
  .surplus-material {
    padding: 10px 20px 5px;
    height: calc(100% - 15px);
    position: relative;
    display: flex;
    flex-direction: column;
  }

  .surplus-material .surplus-material-table-div {
    flex: 1;
    overflow: auto;
  }
</style>

</html>